class SectionController < ApplicationController

 def index
    session[:index_page] = params[:page] == nil ? nil : params[:page]
    @filterrific = initialize_filterrific(Section,params[:filterrific]) or return
    @sections = @filterrific.find.page(params[:page]).order(parent_id: :asc)
 end

 def destroy
   sections = Section.find(params[:id])
   per=Section.per_page.to_i
   child=Section.find_by_sql("select * from sections where parent_id=#{sections.id}")
   person=Person.find_by_sql("SELECT * FROM  user_sys where sections_id=#{sections.id}  ")
   if child.size>0
      notice='请先删除子节点!'
  elsif person.size>0
      notice='请先清空本节点下的关联账号!'
  else
     notice='删除成功'
     sections.destroy
     sum=Section.all
     session[:index_page]=(session[:index_page].to_i - 1).to_s  if sum.size % per ==0 && session[:index_page].to_i >1
  end
     redirect_to section_index_path(page: session[:index_page]), notice: notice
 end

 def new
 end

 def create
      section_name= params[:section_name]
      father_section_name=  params[:father_section_name]
      ref=Section.new
      ref.section_name=section_name
      ref.parent_id=params[:father_id]
      ref.name=father_section_name      
      ref.section_address=params[:section_address]
      ref.section_tel=params[:section_tel]

      if ref.save
          notice="新增成功"
      else
          notice="新增失败"
      end
         redirect_to section_index_path(page: session[:index_page]), notice: notice
 end

 def sec_save   #ajax 调用
      a=params[:a]
      b=params[:b]  #parent_id
      data=Section.find_by_sql("SELECT * FROM sections where section_name='#{a}' and parent_id=#{b}  ")
      if data.size<1
         render text:0   #能保存
      else
         render text:1   #不能保存
      end
 end

def  edit
    sections = Section.find(params[:id]) 
    @section_community = SectionCommunity.new
    @section_name=sections.section_name  
    @section_id=sections.id    
    @dev_sn=MallDictCommunity.find_by_sql("SELECT id,concat(name,'---',IFNULL(address,'') ) name  FROM  dict_community order by name desc ")             
    @dev=[]
    @array_dev=@dev_sn.to_json
    i=0
    while i<JSON(@array_dev).size
      @dev<<JSON(@array_dev)[i]
    i=i+1
    end
end

def new_node 
    note=params[:note]
    section_id=params[:section_id]
    section=Section.find(section_id)
    ref_data=SectionCommunity.where(" section_id=? ",section_id)
    ref_data.destroy_all
    for i in note
        community=MallDictCommunity.find(i)       
        ref= SectionCommunity.new         
        ref.section_id=section_id
        ref.community_id=i
        ref.community_name=community.name
        ref.community_address=community.address
        ref.section_name=section.section_name
        ref.save      
    end
    notice="新增成功"
    redirect_to section_index_path(page: session[:index_page]), notice: notice
end


end
